from django.db import models
from django.contrib.auth.models import User
from docutils.core import publish_parts

# i18n
from django.utils.translation import ugettext_lazy as _

# Create your models here.

class Namespace(models.Model):
	name = models.CharField(max_length = 200, primary_key = True)

	def __unicode__(self):
		return self.name

	class Meta:
		verbose_name = _('namespace')
		verbose_name_plural = _('namespaces')

	class Admin:
		pass

class Page(models.Model):
	name = models.CharField(max_length = 200, primary_key = True)
	namespace = models.ForeignKey(Namespace, null = True, blank = True)
	creationDate = models.DateTimeField(_('creation date'))

	def lastRevision(self):
		try:
			last = Content.objects.filter(page = self).order_by('-lastChangeDate')[0:1].get()
			return last
		except Content.DoesNotExist:
			return None

	def lastRevisionFormatted(self):
		text = self.lastRevision()
		out = ""
		if text:
			parts = publish_parts(source = text.content, writer_name = "html4css1")
			out = parts["html_body"]
		return out

	def orderedRevisionList(self):
		return self.content_set.all().order_by('-lastChangeDate')
			
	def __unicode__(self):
		return self.name
	
	class Meta:
		verbose_name = _('page')
		verbose_name_plural = _('pages')

	class Admin:
		pass

class Content(models.Model):
	# FIXME: Change the name of this class for revision
	page = models.ForeignKey(Page)
	content = models.TextField()
	author = models.ForeignKey(User)
	lastChangeDate = models.DateTimeField(_('last change date'))

	def __unicode__(self):
		return self.content
	
	class Meta:
		verbose_name = _('content')
		verbose_name = _('contents')

	class Admin:
		pass
